package me.kuye.jkuye.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.kuye.jkuye.aop.Invocation;
import me.kuye.jkuye.config.Constants;
import me.kuye.jkuye.handler.Handler;
import me.kuye.jkuye.log.Logger;
import me.kuye.jkuye.render.Render;
import me.kuye.jkuye.render.RenderException;
import me.kuye.jkuye.render.RenderFactory;

public class ActionHandler extends Handler {
	private ActionMapping actionMapping;
	private Constants constants;
	private boolean devMode;
	private static final RenderFactory renderFactory = RenderFactory.getInstance();
	private static final Logger logger = Logger.getLogger(ActionHandler.class);

	public ActionHandler(ActionMapping actionMapping, Constants constants) {
		this.actionMapping = actionMapping;
		this.devMode = constants.getDevMode();
	}

	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		if (target.indexOf('.') != -1) {
			return;
		}
		isHandled[0] = true;
		String[] urlPara = { null };
		Action action = actionMapping.getAction(target, urlPara);
		if (action == null) {
			if (logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("404 Action Not Found: " + (qs == null ? target : target + "?" + qs));
			}
			renderFactory.getErrorRender(404).setContext(request, response).render();
			return;
		}
		try {
			Controller controller = action.getControllerClass().newInstance();
			controller.init(request, response, urlPara[0]);
			if (devMode) {
				boolean isMultipartRequest = ActionReporter.reportCommonRequest(controller, action);
				new Invocation(controller, action).invoke();
				if (isMultipartRequest) {
					ActionReporter.reportMultipartRequest(controller, action);
				}
			} else {
				new Invocation(controller, action).invoke();
			}
			Render render = controller.getRender();
			if (render instanceof ActionRender) {
				String actionUrl = ((ActionRender) render).getActionUrl();
				if (actionUrl.equals(target)) {
					throw new RuntimeException("The forward action url is the same as before.");
				} else {
					handle(actionUrl, request, response, isHandled);
				}
				return;
			}

			if (render == null) {
				render = renderFactory.getDefaultRender(action.getViewPath() + action.getMethodName());
			}
			render.setContext(request, response, action.getViewPath()).render();
		} catch (RenderException e) {
			if (logger.isErrorEnabled()) {
				String qs = request.getQueryString();
				logger.error(qs == null ? target : target + "?" + qs, e);
			}
		} catch (ActionException e) {
			int errorCode = e.getErrorCode();
			if (errorCode == 404 && logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("404 Not Found: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 401 && logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("401 Unauthorized: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 403 && logger.isWarnEnabled()) {
				String qs = request.getQueryString();
				logger.warn("403 Forbidden: " + (qs == null ? target : target + "?" + qs));
			} else if (logger.isErrorEnabled()) {
				String qs = request.getQueryString();
				logger.error(qs == null ? target : target + "?" + qs, e);
			}
			e.getErrorRender().setContext(request, response, action.getViewPath()).render();
		} catch (Throwable t) {
			if (logger.isErrorEnabled()) {
				String qs = request.getQueryString();
				logger.error(qs == null ? target : target + "?" + qs, t);
			}
			renderFactory.getErrorRender(500).setContext(request, response, action.getViewPath()).render();
		}
	}

}
